<template>
  <div>
    <van-nav-bar
      title="商品详情"
      left-text=""
      right-text="精品汇首页"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />

    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item  v-for="item in imageList" :key="item.id" >
        <!--<img :src="item.url" class="img"/>-->
        <van-image
          width="100%"
          height="100%"
          fit="contain"
          :src="item.url"
        />
      </van-swipe-item>
    </van-swipe>

    <div class="columnr">
      <div style="padding-top: 10px;padding-left: 16px;font-size: 16px;font-weight: bold;">
        {{productInfo.name}}
      </div>

      <div style="padding-left: 15px; padding-top: 10px;">
        <label style="font-size: 14px;color: #BAC1CD;">兑换价格：</label>
        <label style="font-size: 16px;color: red;font-weight: bold;"> {{jfnum}}</label>
        <label style="font-size: 16px;color: red;">&nbsp;&nbsp;积分</label>
      </div>

      <div style="font-size: 14px;padding-left: 15px;padding-top: 10px;">
        已选规格：{{skuName}}
      </div>

    </div>





    <div class="qybg">
      <div  class="qytitle">
        产品介绍
      </div>
      <div v-html="productInfo.introduction"/>
    </div>

    <div class="qybg">
      <div style="margin-bottom: 10px"  class="qytitle">
        联系方式
      </div>
      <div style="padding-bottom: 40px;">
        <van-cell-group>
          <van-cell title="联系人" :value="companyInfo.contacts" icon="manager-o" />
          <van-cell title="联系电话" :value="companyInfo.contactsPhone" icon="phone-o" @click="toPhone(companyInfo.contactsPhone)"/>
          <van-cell title="微信" :value="companyInfo.contactsWechat"  icon="chat-o"/>
        </van-cell-group>
      </div>
    </div>
    <!-- <div class="qybg">
       <div style="margin-bottom: 10px"  class="qytitle">
         公司信息
       </div>
       <div>
         <van-cell-group>
           <van-cell title="名称" center :value="companyInfo.name"  icon="wap-home-o" />
           <van-cell title="地址" center :value="companyInfo.provinceName+companyInfo.cityName+companyInfo.countyName+companyInfo.address"  icon="location-o" />
           <van-cell title="电话" :value="companyInfo.phone" icon="phone-o" @click="toPhone(companyInfo.phone)"/>
           <van-cell title="官网" :value="companyInfo.website" icon="desktop-o"/>
         </van-cell-group>
       </div>
     </div>-->

    <van-goods-action>
      <!--<van-goods-action-icon icon="wap-home-o" text="公司首页" @click="onReturn" class="text-class" color="#1989FA"/>-->
      <!--
            <van-goods-action-button type="warning" text="代理咨询" @click="onShowMessage"/>
      -->
      <van-goods-action-button type="danger"  text="立刻购买" @click="onShowSample"/>
    </van-goods-action>

    <div>
      <van-popup
        v-model:show="showBase"
        round
        position="bottom"
        :style="{ height: '50%' }"
      >
        <div style="display: flex;flex-direction: row;padding-top: 10px;padding-left: 10px;">
          <img :src="imageList.length > 0 ? imageList[0].url:'' " style="width: 80px;height: 80px;" />

          <div style="display: flex;flex-direction: column;padding-left: 20px;padding-bottom: 10px;">
            <div style="font-size: 20px;color: red">{{jfnum}} 积分</div>
            <div style="font-size: 14px; color: black;padding-top: 10px;">规格：{{skuName}}</div>
          </div>

        </div>

        <van-divider />
        <van-cell title="请选择购买数量：">
          <van-stepper v-model="buynum" />
        </van-cell>

        <div style="margin-left: 20px;margin-right: 20px;margin-top: 20px;">
          <van-button type="danger" size="large" round @click="doSubmit">确定</van-button>
        </div>
      </van-popup>

    </div>


  </div>
</template>

<script>
  import AreaList from '../../../static/area'
  import { getCompanyInfo, getProductInfo, saveAgencyChat,addReadLog ,queryProperties ,queryProductSku } from '../../api/api'
  import { Dialog, Toast } from 'vant'
  import { saveApplySample } from 'api/api'
  import skuData  from './skuData'

  export default {
    name: 'Product',
    data() {
      return {
        companyId: null,
        productId: null,
        productInfo: {},
        companyInfo: {},
        imageList: [],
        showMessage: false,
        showSample: false,
        areaList: AreaList,
        showArea: false,
        form: {},
        formSample: {},
        agencyId:null,
        btnname:'申请样品',
        showgwc:false,
        skuData:skuData,
        showBase: false,
        showCustom: false,
        showStepper: false,
        showSoldout: false,
        closeOnClickOverlay: true,
        initialSku:{
          s1: "0001",
          s2: "1001",
          selectedNum: 1
        },
        skuName:'',
        properties:'',
        skuId:'',
        jfnum:'',
        buynum:1


      }
    },
    created() {
      let  agencyId = this.$route.query.agencyId

      if(!agencyId){
        agencyId = this.$store.getters.agencyId
      }else {
        this.$store.dispatch('setAgencyId', agencyId)
      }

      this.companyId = this.$route.query.companyId
      this.productId = this.$route.query.productId
      this.skuName = this.$route.query.skuName
      this.properties = this.$route.query.properties
      this.skuId = this.$route.query.skuId
      this.jfnum = this.$route.query.jfnum

      console.log('agencyid:' + agencyId)
      if(agencyId){
        console.log('agencyid:' + agencyId)
        const param = { agencyid:agencyId ,companyId:this.companyId,productId:this.productId}
        console.log(param)
        addReadLog(param).then(response => {

        })
      }


      if(this.$route.query.productId == 153){
        this.btnname = '留言购买'
      }
      this.agencyId = agencyId


      this.getProductInfo()
      this.getCompanyInfo()
      this.getSkuInfo()
    },
    methods: {
      getProductInfo() {
        const param = { productId: this.productId }
        getProductInfo(param).then(response => {
          this.productInfo = response.data
          if(this.productInfo.introduction){
            this.productInfo.introduction = this.formatRichText(this.productInfo.introduction)
          }
          const resultImage = []
          if (typeof this.productInfo.image1 !== 'undefined' && this.productInfo.image1 !== '' && this.productInfo.image1 !== null) {
            resultImage.push({ id: 1, url: this.productInfo.image1 })
          }
          if (typeof this.productInfo.image2 !== 'undefined' && this.productInfo.image2 !== '' && this.productInfo.image2 !== null) {
            resultImage.push({ id: 2, url: this.productInfo.image2 })
          }
          if (typeof this.productInfo.image3 !== 'undefined' && this.productInfo.image3 !== '' && this.productInfo.image3 !== null) {
            resultImage.push({ id: 3, url: this.productInfo.image3 })
          }
          if (typeof this.productInfo.image4 !== 'undefined' && this.productInfo.image4 !== '' && this.productInfo.image4 !== null) {
            resultImage.push({ id: 4, url: this.productInfo.image4 })
          }
          if (typeof this.productInfo.image5 !== 'undefined' && this.productInfo.image5 !== '' && this.productInfo.image5 !== null) {
            resultImage.push({ id: 5, url: this.productInfo.image5 })
          }
          if (typeof this.productInfo.image6 !== 'undefined' && this.productInfo.image6 !== '' && this.productInfo.image6 !== null) {
            resultImage.push({ id: 6, url: this.productInfo.image6 })
          }
          this.imageList = resultImage
          skuData.sku.price = this.productInfo.price
          console.log('商品信息：',this.productInfo)
          this.queryProductPropertyValue()
          this.queryProductSku()
        })
      },

      getSkuInfo(){
        const param = {productId : this.productId}
      },

      onAddCartClicked(){

      },

      formatRichText(richText){
        if(richText != null){
          let newRichText= richText.replace(/<img[^>]*>/gi,function(match,capture){
            match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
            match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
            match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
            return match;
          });
          newRichText = newRichText.replace(/style="[^"]+"/gi,function(match,capture){
            match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
            return match;
          });
          newRichText = newRichText.replace(/<br[^>]*\/>/gi, '');
          newRichText = newRichText.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
          return newRichText;
        }else{
          return null;
        }
      },

      getCompanyInfo() {
        const param = { companyId: this.companyId }
        getCompanyInfo(param).then(response => {
          this.companyInfo = response.data
        })
      },

      onClickLeft() {
        this.$router.go(-1) // 返回上一层
      },

      onClickRight(){
        this.$router.push({ path: '/home', query: { agencyId: this.agencyId }})
      },

      onShowMessage() {
        this.showMessage = true
      },
      onShowSample() {
        this.showBase = true
      },
      onReturn() {
        this.$router.push({ path: '/company', query: { companyId: this.companyId }})
        // this.$router.go(-1) // 返回上一层
      },
      onConfirmArea(values) {
        console.log(values)
        this.form.province = values[0].name
        this.form.city = values[1].name
        this.form.county = values[2].name

        const dlqy = values
          .filter((item) => !!item)
          .map((item) => item.name)
          .join('/')
        this.form.dlqy = dlqy
        this.showArea = false
      },
      saveAgencyChat() {
        const agencyId = this.$store.getters.agencyId
        const productId = this.productId
        const param = { ...this.form, companyId: this.companyId, agencyId: agencyId,productId:productId }
        debugger
        saveAgencyChat(param).then(response => {
          console.log(response)
          if (response.code === 200) {
            this.showMessage = false
            Dialog.alert({
              title: '',
              message: '提交成功'
            }).then(() => {
              // on close
            })
          } else {
            Toast.fail(response.msg)
          }
        })
      },

      saveApplySample() {
        let agencyId = this.$store.getters.agencyId
        let that = this
        if(!agencyId){
          agencyId = that.agencyId
        }
        const productId = this.productId
        const param = { ...this.formSample, companyId: this.companyId, agencyId: agencyId,productId: productId }
        saveApplySample(param).then(response => {
          console.log(response)
          if (response.code === 200) {
            this.showSample = false
            Dialog.alert({
              title: '',
              message: '提交成功'
            }).then(() => {
              // on close
            })
          } else {
            Toast.fail(response.msg)
          }
        })
      },

      toPhone(phone) {
        window.location.href = 'tel://' + phone
      },


      queryProductPropertyValue(){
        let param = {}
        param.productId = this.productInfo.productId
        queryProperties(param).then(response => {
          let propertyList = response.rows
          let tree = []
          if(propertyList.length > 0 ){
            for(var i=0;i<propertyList.length;i++){
              let temp = {}
              let vArray = []
              temp.k = propertyList[i].name
              temp.k_id = propertyList[i].propertyId
              temp.k_s = 's' + ( i + 1 )
              temp.count = 10
              let list = propertyList[i].list
              for(var j = 0 ; j<list.length;j++){
                let temp1 = {}
                temp1.id = list[j].valueId
                temp1.name = list[j].name
                temp1.imgUrl = list[j].imageUrl
                vArray.push(temp1)
              }
              temp.v = vArray
              tree.push(temp)
            }
            skuData.sku.tree = tree

          }

        });

      },

      queryProductSku(){
        let param = {}
        param.productId = this.productInfo.productId
        queryProductSku(param).then(response => {
          let stock_total  =  0

          let productSkuList = response.rows
          console.log(productSkuList)
          let list = []
          if(productSkuList.length > 0 ){
            for(var i=0;i<productSkuList.length;i++){

              stock_total += productSkuList[i].stock
              let temp = {}
              temp.id = productSkuList[i].skuId
              temp.price = productSkuList[i].price * 100
              temp.discount = ''
              temp.stock_num = productSkuList[i].stock
              temp.goods_id = this.productInfo.productId
              let properties = productSkuList[i].properties
              let propArray = []
              if(properties){
                var str1Array = properties.split(',')
                if(str1Array.length > 0 ){
                  for(var j=0;j<str1Array.length;j++){
                    var str2Array = str1Array[j].split(':')
                    propArray.push(str2Array[1])
                  }
                }
              }
              if(propArray.length >= 1 ){
                temp.s1 = propArray[0]
              }else{
                temp.s1 = '0'
              }
              if(propArray.length >= 2 ){
                temp.s2 = propArray[1]
              }else{
                temp.s2 = '0'
              }
              if(propArray.length >= 3 ){
                temp.s3 = propArray[2]
              }else{
                temp.s3 = '0'
              }

              if(propArray.length >= 4 ){
                temp.s4 = propArray[3]
              }else{
                temp.s4 = '0'
              }

              if(propArray.length >= 5 ){
                temp.s5 = propArray[4]
              }else{
                temp.s5 = '0'
              }

              list.push(temp)

            }

          }

          skuData.sku.list = list
          skuData.sku.stock_num = stock_total
          skuData.sku.none_sku = false // 是否无规格商品
          skuData.sku.hide_stock = false  // 是否隐藏剩余库存
          skuData.goods_id = this.productInfo.productId
          let goodsInfo = { }
          goodsInfo.title = this.productInfo.name
          goodsInfo.picture = this.productInfo.image1
          skuData.goods_info = goodsInfo
        });


      },

      onBuyClicked(data){
        console.log('确定',data)

        this.$router.push({ path: '/confirmOrder', query:{selectedNum : data.selectedNum , productId : data.selectedSkuComb.goods_id , price:data.selectedSkuComb.price / 100 , skuId:data.selectedSkuComb.id ,addressId:'',agencyId:this.agencyId } })

      },


      doSubmit(){
        this.showBase = false
        this.$router.push({ path: '/confirmJfOrder', query:{selectedNum : this.buynum , productId :this.productId , price:this.jfnum , skuId:this.skuId ,addressId:'',agencyId:this.agencyId } })
      },

      customSkuValidator(data){
        console.log('校验',data )
      }


    }
  }
</script>

<style scoped>
  .my-swipe .van-swipe-item {
    color: #fff;
    font-size: 20px;
    height: 280px;
    text-align: center;
    background-color: #ffffff;
  }
  .img{
    height: 100%;
    width: 100%;
  }
  .qybg{
    width: 100%;
    background-color: #ffffff;
    padding:10px;
    margin-top: 5px;
    box-sizing:border-box;
  }
  .qytitle{
    font-size: 14px;
    font-weight: bold;
    padding-left: 10px;
  }

  .text-class{
    color: #1989FA !important;
  }

  .rownr{
    display: flex;
    flex-direction: row;
    padding-top: 10px;
    margin-bottom: 10px;
    background-color: white;
  }

  .columnr{
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    padding-bottom: 20px;
    margin-bottom: 10px;
    background-color: white;
  }
</style>
